package com.mcxx.util;

import com.mcxx.result.BaseResult;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IdCardUtil {
    public static String getBirthDay(String id) {
        String year = null;
        String month = null;
        String day = null;

        if (id.matches("^\\d{15}|\\d{17}[\\dxX]$")) {
            year = id.substring(6, 10);
            month = id.substring(10, 12);
            day = id.substring(12, 14);
        } else {
            System.out.println("身份证号码不匹配！");
            return null;
        }
        return year + "-" + month + "-" + day;
    }


    public static Integer getAge(String cardId) {
        Integer age = null;
        try {
            age = getAgeByBirth(DateUtil.sdf2.parse(getBirthDay(cardId)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return age;
    }
    public static String getSex(String cardId) {
        String temp = "";
        if (!CommonUtil.invalidArgs(cardId) && cardId.length() == 18) {
            temp = cardId.substring(16, 17);
            if (Integer.parseInt(temp) % 2 == 0) {
                temp = "2";
            } else {
                temp = "1";
            }
        }
        return temp;
    }


    public static int getAgeByBirth(Date birthDay) throws ParseException {
        int age = 0;
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }



    public static BaseResult<Boolean> identityCardVerification(String idStr) {
        BaseResult<Boolean> resultMessage = new BaseResult<Boolean>();
        String[] wf = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
        String[] checkCode = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2" };
        String iDCardNo = "";
        try {

            if (idStr.length() != 15 && idStr.length() != 18) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10030.getCode());
                resultMessage.setMsg(FailureCode.ERR_10030.getMessage());
                return resultMessage;
            }
            if (idStr.length() == 18) {
                iDCardNo = idStr.substring(0, 17);
            } else if (idStr.length() == 15) {
                iDCardNo = idStr.substring(0, 6) + "19" + idStr.substring(6, 15);
            }
            if (isStrNum(iDCardNo) == false) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10031.getCode());
                resultMessage.setMsg(FailureCode.ERR_10031.getMessage());
                return resultMessage;
            }
            idStr=idStr.toUpperCase();

            String strYear = iDCardNo.substring(6, 10);
            String strMonth = iDCardNo.substring(10, 12);
            String strDay = iDCardNo.substring(12, 14);
            if (isStrDate(strYear + "-" + strMonth + "-" + strDay) == false) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10032.getCode());
                resultMessage.setMsg(FailureCode.ERR_10032.getMessage());
                return resultMessage;
            }
            GregorianCalendar gc = new GregorianCalendar();
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
            if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150 || (gc.getTime().getTime() - s.parse(strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10033.getCode());
                resultMessage.setMsg(FailureCode.ERR_10033.getMessage());
                return resultMessage;
            }
            if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10034.getCode());
                resultMessage.setMsg(FailureCode.ERR_10034.getMessage());
                return resultMessage;
            }
            if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10035.getCode());
                resultMessage.setMsg(FailureCode.ERR_10035.getMessage());
                return resultMessage;
            }

            Hashtable h = GetAreaCode();
            if (h.get(iDCardNo.substring(0, 2)) == null) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10036.getCode());
                resultMessage.setMsg(FailureCode.ERR_10036.getMessage());
                return resultMessage;
            }

            int theLastOne = 0;
            for (int i = 0; i < 17; i++) {
                theLastOne = theLastOne + Integer.parseInt(String.valueOf(iDCardNo.charAt(i))) * Integer.parseInt(checkCode[i]);
            }
            int modValue = theLastOne % 11;
            String strVerifyCode = wf[modValue];

            //System.out.println(strVerifyCode);
            iDCardNo = iDCardNo + strVerifyCode;
            if (idStr.length() == 18 &&!iDCardNo.equals(idStr)) {
                resultMessage.setData(false);
                resultMessage.setCode(FailureCode.ERR_10037.getCode());
                resultMessage.setMsg(FailureCode.ERR_10037.getMessage());
                return resultMessage;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        resultMessage.setData(true);
        resultMessage.setCode(FailureCode.SUC_0.getCode());
        resultMessage.setMsg(FailureCode.SUC_0.getMessage());
        return resultMessage;
    }


    private static Hashtable GetAreaCode() {
        Hashtable hashtable = new Hashtable();
        hashtable.put("11", "北京");
        hashtable.put("12", "天津");
        hashtable.put("13", "河北");
        hashtable.put("14", "山西");
        hashtable.put("15", "内蒙古");
        hashtable.put("21", "辽宁");
        hashtable.put("22", "吉林");
        hashtable.put("23", "黑龙江");
        hashtable.put("31", "上海");
        hashtable.put("32", "江苏");
        hashtable.put("33", "浙江");
        hashtable.put("34", "安徽");
        hashtable.put("35", "福建");
        hashtable.put("36", "江西");
        hashtable.put("37", "山东");
        hashtable.put("41", "河南");
        hashtable.put("42", "湖北");
        hashtable.put("43", "湖南");
        hashtable.put("44", "广东");
        hashtable.put("45", "广西");
        hashtable.put("46", "海南");
        hashtable.put("50", "重庆");
        hashtable.put("51", "四川");
        hashtable.put("52", "贵州");
        hashtable.put("53", "云南");
        hashtable.put("54", "西藏");
        hashtable.put("61", "陕西");
        hashtable.put("62", "甘肃");
        hashtable.put("63", "青海");
        hashtable.put("64", "宁夏");
        hashtable.put("65", "新疆");
        hashtable.put("71", "台湾");
        hashtable.put("81", "香港");
        hashtable.put("82", "澳门");
        hashtable.put("91", "国外");
        return hashtable;
    }


    private static boolean isStrNum(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        } else {
            return false;
        }
    }


    public static boolean isStrDate(String strDate) {
        Pattern pattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))" +
				"[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|" +
				"(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))" +
				"[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))" +
				"[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s((" +
				"(0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }


    private static String getCheckCodeBySum(int sum17) {
        String checkCode = null;
        switch (sum17 % 11) {
            case 10:
                checkCode = "2";
                break;
            case 9:
                checkCode = "3";
                break;
            case 8:
                checkCode = "4";
                break;
            case 7:
                checkCode = "5";
                break;
            case 6:
                checkCode = "6";
                break;
            case 5:
                checkCode = "7";
                break;
            case 4:
                checkCode = "8";
                break;
            case 3:
                checkCode = "9";
                break;
            case 2:
                checkCode = "X";
                break;
            case 1:
                checkCode = "0";
                break;
            case 0:
                checkCode = "1";
                break;
            default:
        }
        return checkCode;
    }

}
